package org.zzz.hepotaiya.util;

import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.zzz.hepotaiya.exception.BatchLoadException;

import bsh.classpath.BshClassPath;

public class ClassUtils {

	/**
	 * 指定文字を含むClassListを返却します
	 * @param findKey
	 * @return Classリスト
	 * @throws Exception
	 */
	public static List<Class> findLoadedClasses(String findKey) throws Exception {
		if (StringUtils.isEmpty(findKey)) {
			return new ArrayList<Class>();
		}
		try {
			List<Class> ret = new ArrayList<Class>();
			BshClassPath bcp = BshClassPath.getUserClassPath();
			Iterator<String> packageIterator = bcp.getPackagesSet().iterator();
			while (packageIterator.hasNext()) {
				String packageString = packageIterator.next();
				Iterator<String> classIterator = bcp.getClassesForPackage(packageString).iterator();
				while (classIterator.hasNext()) {
					String className = (String)classIterator.next();
					if ((className.indexOf("$") >= 0) || (className.indexOf(findKey) == -1)) {
						continue;
					}
					Class clazz = Class.forName(className);
					int modifier = clazz.getModifiers();
					if (Modifier.isAbstract(modifier)) {
						continue;
					}
					if (Modifier.isInterface(modifier)) {
						continue;
					}
					ret.add(clazz);
				}
			}
			return ret;
		} catch (Exception e) {
			throw new BatchLoadException(e);
		}
	}
}
